package _05_二叉树;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * https://leetcode-cn.com/problems/binary-tree-inorder-traversal/
 */
public class _94_二叉树的中序遍历 {

    // 递归
    public List<Integer> inorderTraversal1(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        inorderTraversal(root, list);
        return list;
    }

    public void inorderTraversal(TreeNode node, List<Integer> list) {
        if (node == null) return;

        inorderTraversal(node.left, list);

        list.add(node.val);

        inorderTraversal(node.right, list);
    }

    // 迭代，模拟栈结构
    public List<Integer> inorderTraversal2(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        if (list == null) return list;
        Stack<TreeNode> stack = new Stack<>();
        while (true) {
            if (root != null) {
                stack.push(root);
                root = root.left;
            } else {
                if (stack.isEmpty()) {
                    break;
                } else {
                    // 弹出元素
                    TreeNode node = stack.pop();
                    list.add(node.val);
                    if (node.right != null) {
                        root = node.right;
                    }
                }
            }

        }
        return list;
    }

    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        if (root == null) return list;
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        // 记录上一次访问的节点
        TreeNode prev = null;
        while (!stack.isEmpty()) {
            TreeNode node = stack.pop();
            // 获取前驱节点
            TreeNode predecessor = node.left;
            if (predecessor != null) {
                while (predecessor.right != null) {
                    predecessor = predecessor.right;
                }
            }
            // 前驱节点为空，或者等于上个节点，则访问根节点
            if (predecessor == null || predecessor == prev) {
                list.add(node.val);
                prev = node;
                // 右节点入栈
                if (node.right != null) stack.push(node.right);
            } else {
                // 入栈当前节点
                stack.push(node);
                // 访问左节点
                if (node.left != null) stack.push(node.left);
            }
        }
        return list;
    }
}
